package com.xxxx.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xzl.tool.util.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


/**
 * @Author Lionel
 * @Date 2020/10/16 11:16
 * Created by IntelliJ IDEA 2020.1.
 * Project: yeb_back
 * Description：验证码控制层
 */
@Slf4j
@RestController
@Api(tags = "验证码CaptchaController")
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha")
    public RespBean captcha(HttpServletRequest request, HttpServletResponse response) {
        //-------------------设置验证码--------------------------
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");

        //-------------------生成验证码 begin --------------------------
        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        System.out.println("验证码内容：" + text);
        //将验证码放入session中
        request.getSession().setAttribute("captcha", text);
        String captcha = (String) request.getSession().getAttribute("captcha");
        System.out.println("neo:"+captcha);
        //根据文本内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
//        ServletOutputStream outputStream = null;

        ByteArrayOutputStream outputStream = null;
        outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String imageStr = encoder.encode(outputStream.toByteArray());
        return RespBean.success("ok",imageStr);
    }

}
